<?php
namespace app\api\controller\xiservice;


use addons\xiservice\controller\WeixinMini;
use app\common\controller\xiservice\XiserviceApi;
use app\common\model\xiservice\User as XiserviceUser;
use app\common\model\xiservice\Order;
use app\common\model\xiservice\Address;
use app\common\model\xiservice\Collect;
use app\common\library\Sms;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\ThrowableError;
use think\Validate;


/**
 * 用户模块
 */
class User extends XiserviceApi
{
    protected $noNeedLogin = ['wxlogin','wxNumberEncrypted','miniconfig'];
    protected $noNeedRight = ['*'];
    


    /**
     * @ApiTitle (用户个人信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.user/profile)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','username':'string','avatar':'string','mobile':'int','addressnums':'int','collectnums':'int','ordernums':'int'}", description="返回数据")
     */
    public function profile() {
       
        $user = XiserviceUser::where('user_id',$this->auth->id)->field('images,contact_name,privacy,user_id,username,mobile,avatar,checkinfo,group_id,vip_type,vip_end_time')->where(['status'=>1])->find();
        if($user){
             $user['addressnums'] = Address::where('user_id',$this->auth->id)->count();
             $user['collectnums'] = Collect::where('user_id',$this->auth->id)->count();
             $user['ordernums'] = Order::where('user_id',$this->auth->id)->where('order_type',10)->count();
             $user['zjordernums'] = Order::where('user_id',$this->auth->id)->where('order_type',20)->count();

             if($user['vip_end_time'] < time()){
                 $user['vip_end_time'] = '';
                 $user['vip_type'] = '';
             } else {
                 $user['vip_end_time'] = date('Y-m-d H:i', $user['vip_end_time']);
             }

             //是否是师傅
            if($user['checkinfo'] == 1 && $user['group_id'] == 2) {
                $user['is_master'] = 1;
            } else {
                $user['is_master'] = 0;
            }

        }else
        {
            $this->error('用户已禁用',null,-1);

        }
        
        $this->success('查询成功',$user);
    }

    /**
     * @ApiTitle (编辑用户个人信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.user/edit_profile)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{}", description="返回数据")
     */
    public function edit_profile() {
       
        $username = $this->request->post('name');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if(!$username){
            $this->error('参数错误');
        }
        $user = XiserviceUser::where('user_id',$this->auth->id)->field('user_id,username,mobile,avatar')->find();
        $user->username = $username;
        $user->avatar = $avatar;
        $user->save();
        $this->success('更新成功');
    }

    /**
     * @ApiTitle (用户推广海报)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.user/poster)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'id':'int','name':'string','image':'string','bargain':'int','saleprice':'float','basicnums':'int','salenums':'int'}", description="返回数据")
     */
    public function poster()
    {
        $wx = new WeixinMini();
        $user_id = $this->auth->id;
        $user = XiserviceUser::where('user_id',$this->auth->id)->find();
        if (!$user['miniapp_code']) {
            // $response=$wx->app->app_code->get('pages/index/index?code=='.$user['mini_openid'], ['width' => 300]);
            $qrcode_url = sprintf('pages/index/index?code=%s&uid=%s', $user['mini_openid'], $user_id);
            $response=$wx->app->app_code->get($qrcode_url, ['width' => 300]);

            $local_folder = ROOT_PATH . 'public/poster/'; // 本地绝对路径，存放生成的二维码
            $filename = md5(time()) . '-'.mt_rand(1000,9999).'.png';
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs($local_folder, $filename);
            }  
            $path = '/poster/'.$filename;
            XiserviceUser::where('user_id',$this->auth->id)->update(['miniapp_code'=>$path]);
            $this->success('查询成功',cdnurl($path,true));
        }
        $this->success('查询成功',cdnurl($user['miniapp_code'],true));
    }

    public function agreement()
    {
         Db::name('xiservice_user')->where(['user_id'=>$this->auth->id])->update(['privacy'=>1]);
         $this->success('查询成功');
    }
   
    /**
     * @ApiTitle (获取微信小程序头像)
     * @ApiRoute (/api/xiserivce.user/miniconfig)
     * @ApiMethod (GET)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     */
    public function miniconfig()
    {
        $logo = isset(config('xiservice.wxmini')['wxmini_logo'])?config('xiservice.wxmini')['wxmini_logo']:'';
        if(!$logo){
            $this->success('查询成功','');
        }
        $this->success('查询成功',cdnurl($logo,true));
    }


    /**
     * @ApiTitle (微信登录)
     * @ApiRoute (/api/xiserivce.user/wxlogin)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="string", required=true, description="微信登录code")
     * @ApiParams (name="iv", type="string", required=true, description="iv")
     * @ApiParams (name="encryptedData", type="string", required=true, description="encryptedData")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     */
    public function wxlogin()
    {
        $code = $this->request->post('code');
        $iv = $this->request->post('iv','','');
        $encryptedData = $this->request->post('encryptedData','','');

        $wx = new WeixinMini();
        $iv = $wx->define_str_replace($iv);
        $encryptedData = $wx->define_str_replace($encryptedData);
        $userinfo = [];
        try {
            $data = $wx->wxlogin($code);
            if (!isset($data['openid'])) {
                 throw new Exception('微信获取信息错误!');
            }
            $wxdata = $wx->wxEncrypted($data['session_key'],$iv, $encryptedData);

            $xiserviceuser = XiserviceUser::where('mini_openid',$data['openid'])->find();   
            if(!$xiserviceuser){
                $this->error('请先获取微信手机号码授权!',[]);
            }

            $UserData['nickname']= $wxdata['nickName'];
            if(empty($xiserviceuser['username'])) {
                $UserData['username']= $wxdata['nickName'];
                $UserData['avatar']= $wxdata['avatarUrl'];
            }

            $res = XiserviceUser::where('user_id',$xiserviceuser['user_id'])->update($UserData);
            $user = \app\common\model\User::where('id',$xiserviceuser['user_id'])->update($UserData);
            $ret = $this->auth->direct($xiserviceuser['user_id']);
            $userinfo = $this->auth->getUserinfo();

            if($userinfo['status']!='normal')
            {
                $this->error('用户已禁用',null,-1);
            }
            // echo "<pre>";
            // print_r($userinfo);die;


            $userinfo = array_merge($userinfo,$UserData);
        }catch (ThrowableError $e){
            $this->error($e->getMessage());
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        

        $this->success('登陆成功', $userinfo);
    }

    /**
     * @ApiTitle (微信手机号解密)
     * @ApiRoute (/api/xiservice.user/wxNumberEncrypted)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="int", required=true, description="微信登陆code")
     * @ApiParams (name="iv", type="string", required=true, description="iv")
     * @ApiParams (name="encryptedData", type="string", required=true, description="encryptedData")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     */
    public function wxNumberEncrypted()
    {
        $pid           = $this->request->post('uid', 0);
        $code          = $this->request->post('code');
        $iv            = $this->request->post('iv', '', '');
        $encryptedData = $this->request->post('encryptedData', '', '');

        $wx = new WeixinMini();
        $iv = $wx->define_str_replace($iv);
        $encryptedData = $wx->define_str_replace($encryptedData);
        if (!isset(config('xiservice.wxmini')['wxmini_appid'])) {
            $this->error('请先配置小程序appid信息!');
        }       
        Db::startTrans();
        try {
            $data = $wx->wxlogin($code);
            $wxdata = $wx->wxEncrypted($data['session_key'], $iv, $encryptedData);
            $user = \app\common\model\User::where('mobile', $wxdata['phoneNumber'])->find();
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('用户已禁用'));
                }
                //判断是否已经有身份了
                $xiserviceuser = XiserviceUser::where('user_id', $user['id'])->find();
                #创建用户身份账号
                if (!$xiserviceuser) {
                        $xiserviceUserData['mini_openid'] = $data['openid'];
                        $xiserviceUserData['mobile'] = $wxdata['phoneNumber'];
                        $xiserviceUserData['user_id'] = $user['id'];
                        $xiserviceUserData['group_id'] = 1;
                        XiserviceUser::create($xiserviceUserData);
                } else{
                      //如果已经有账号更新openid
                      $xiserviceUserData['mini_openid'] = $data['openid'];
                      $res = XiserviceUser::where('user_id',$user['id'])->update($xiserviceUserData);
                }
            } else {
                // 没有账号 则创建账号
                $ret = $this->auth->register($wxdata['phoneNumber'], Random::alnum(), '', $wxdata['phoneNumber'], ['pid' => $pid]);
                 if ($ret) {
                    $userinfo = $this->auth->getUserinfo();
                    //判断是否已经有身份了
                    $xiserviceuser = XiserviceUser::where('user_id', $userinfo['id'])->find();
                    #创建用户身份账号
                    if (!$xiserviceuser) {
                        $xiserviceUserData['mini_openid'] = $data['openid'];
                        $xiserviceUserData['mobile']      = $wxdata['phoneNumber'];
                        $xiserviceUserData['user_id']     = $userinfo['id'];
                        $xiserviceUserData['group_id']    = 1;
                        XiserviceUser::create($xiserviceUserData);
                    }      
                } else {
                    $this->error($this->auth->getError());
                }          
            }

        } catch (DecryptException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (ThrowableError $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error('用户已禁用');
        }
        Db::commit();
        $this->success(__('操作成功'), []);
    }

    /**
     * @ApiTitle (业务员团队列表)
     * @ApiRoute (/api/xiservice.user/team_list)
     * @ApiMethod (GET)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="page", type="integer", description="页码")
     * @ApiParams  (name="rows", type="integer", description="页数")
     * 
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function team_list()
    {
        $user_id = $this->auth->id;

        // - 验证用户是否业务员
        $service_user_info = XiserviceUser::where('user_id', $user_id)->find();
        if (empty($service_user_info)) {
            $this->error('获取不到用户信息');
        } else if ($service_user_info['group_id'] != 4) {
            $this->error('该用户不是业务员');
        }

        $lists = XiserviceUser::field('user_id as id, username, avatar')
            ->where('parent_user_id', $user_id)
            ->paginate(10);
        $this->success('查询成功', $lists);
    }



}